package serverx

import (
	"strings"
	"time"

	"gitee.com/workits/pkgs/logx"
	"github.com/gin-gonic/gin"
)

func WithAccesslog() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		logx.Infof(
			"access log",
			logx.String("type", "access"),
			logx.String("method", ctx.Request.Method),
			logx.String("path", ctx.Request.URL.Path),
			logx.String("ip", GetClientIP(ctx)),
			logx.String("userAgent", ctx.GetHeader("User-Agent")),
			ctx.Request.Context(),
		)

		start := time.Now()
		ctx.Next()

		logx.Infof(
			"access timing",
			logx.String("type", "access"),
			logx.Int64("timing", time.Now().UnixMilli()-start.UnixMilli()),
			ctx.Request.Context(),
		)
	}
}

func GetClientIP(ctx *gin.Context) string {
	ip := ctx.Request.Header.Get("X-Real-IP")
	if len(ip) == 0 {
		ip = ctx.Request.Header.Get("X-Forwarded-For")
	}
	if len(ip) == 0 {
		ip = ctx.ClientIP()
	}
	if idx := strings.Index(ip, ":"); idx > -1 {
		return ip[:idx]
	}
	return ip
}
